//
//  MapViewController.m
//  ACSProduct
//
//  Created by gaurav on 09/10/11.
//  Copyright 2011 dhillon. All rights reserved.
//

#import "MapViewController.h"


@implementation MapViewController
@synthesize arrayMapLocs,isFromDetail;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

-(void)Direction
{
    Class itemClass = [MKMapItem class];
    if (itemClass && [itemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) {
        MKMapItem *currentLocationItem = [MKMapItem mapItemForCurrentLocation];
        
        MKPlacemark *place = [[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(locationUser.userloc.coordinate.longitude,locationUser.userloc.coordinate.longitude) addressDictionary:nil];
        MKMapItem *destinamtionLocItem = [[MKMapItem alloc] initWithPlacemark:place];
//        destinamtionLocItem.name = [natObject name];
        NSArray *mapItemsArray = [NSArray arrayWithObjects:currentLocationItem, destinamtionLocItem, nil];
        NSDictionary *dictForDirections = [NSDictionary dictionaryWithObject:MKLaunchOptionsDirectionsModeDriving forKey:MKLaunchOptionsDirectionsModeKey];
        [MKMapItem openMapsWithItems:mapItemsArray launchOptions:dictForDirections];
    } else{
        
        //using iOS 5 which has the Google Maps application
//        NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=Current+Location&daddr=%f,%f", latitude, longitude];
//        [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];

        NSString *stringURL = [NSString stringWithFormat:LINKMAPURL,locationUser.strUserLat,locationUser.strUserLong,[[arrayLatLong objectAtIndex:0] objectForKey:FIELDLAT],[[arrayLatLong objectAtIndex:0] objectForKey:FIELDLONG]];
        NSLog(@"%@",stringURL);
        
        NSURL *url = [NSURL URLWithString:stringURL];
        [[UIApplication sharedApplication] openURL:url];

    }
    
    
        
    //    NSString *latlong = [NSString stringWithFormat:@"%@%@",[dictDetails objectForKey:@"lat"],[dictDetails objectForKey:@"lng"]];
    //    
    //    NSString *url = [NSString stringWithFormat: @"http://maps.google.com/maps?ll=%@",
    //                     [latlong stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //    
    //    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    //    NSString *address = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@",textAddress.text];
    //    NSString *escaped_address =  [address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    //    [[UIApplication sharedApplication] openURL:[[NSURL alloc] initWithString:escaped_address]];
}



#pragma mark - View lifecycle
//- (void)viewDidAppear:(BOOL)animated
//{
//    NSLog(@"did appear");
//    [self loadMap];
//}

-(void)pressDoneForSel:(NSString *)stringSel withindex:(NSInteger)indexRow
{
    pickerDis.hidden = YES;
    arrayNearBy = [[NSMutableArray  alloc] init];
    
    if(indexRow != 0)
    {
    for(int i=0;i<[arrayAllData count];i++)
    {
        NSLog(@"%@ --%@",[[arrayFilter objectAtIndex:indexRow-1] objectForKey:@"Id"],[[arrayAllData  objectAtIndex:i]objectForKey:FIELDTYPE]);
        if([[[arrayFilter objectAtIndex:indexRow-1] objectForKey:@"Id"] isEqualToString:[[arrayAllData  objectAtIndex:i]objectForKey:FIELDTYPE]])
        {
            [arrayNearBy addObject:[arrayAllData  objectAtIndex:i]];
        }
    }
    }
    else
    {
        arrayFilter = [[NSMutableArray  alloc] initWithArray:arrayAllData];
    }
    
    [self loadMap];
    
}

-(void)filterBycat
{
    [self.view bringSubviewToFront:pickerDis];
    NSLog(@"%s",__PRETTY_FUNCTION__);
    pickerDis.hidden = NO;
}


- (void)viewDidLoad
{
   
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor] ];

    [self.navigationItem setTitle:MAPTITLE];
    
    self.navigationItem.hidesBackButton = YES;
    //[self functionToCheckLat:arrayMapContent]];
    if(self.isFromDetail == 0)
    {
        [self setPickerView];
         [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem  alloc] initWithTitle:@"Filter By" style:UIBarButtonItemStyleDone target:self action:@selector(filterBycat)]];
        
        [[NSNotificationCenter  defaultCenter] addObserver:self
                                                  selector:@selector(datareload:) 
                                                      name:KsReLOADDATAMETERRAN
                                                    object:nil];
        
        [self tableViewSettingWithRad:50];
    }
    else    
        [self loadMap];
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
}

-(void)setPickerView
{
    NSString *filePath	= [[NSBundle mainBundle]pathForResource:@"ListCat" ofType:@"xml"];
	NSString *fileContents= [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    
    NSDictionary *_xmlDictionaryData = [XMLReader dictionaryForXMLData:[fileContents dataUsingEncoding:NSUTF8StringEncoding] error:nil] ;
    
    
    arrayFilter = [[NSMutableArray alloc] init];
    
    NSMutableArray *arrayCatName = [[NSMutableArray alloc] init];
    [arrayCatName addObject:@"All"];
    
    for(int i=0;i<[[[_xmlDictionaryData objectForKey:@"categories"]objectForKey:@"catagory"] count];i++)
    {
        if([[[[[_xmlDictionaryData objectForKey:@"categories"]objectForKey:@"catagory"] objectAtIndex:i] objectForKey:@"CatInd"] isEqualToString:@"1"])
        {
            [arrayCatName addObject:[[[[_xmlDictionaryData objectForKey:@"categories"]objectForKey:@"catagory"] objectAtIndex:i] objectForKey:@"Name"]];
            
            [arrayFilter addObject:[[[_xmlDictionaryData objectForKey:@"categories"]objectForKey:@"catagory"] objectAtIndex:i] ];
        }
        
    }
    
    pickerDis = [[ViewPickerTool alloc] initWithFrame:CGRectMake(0, 100, 320, 194)];
    [self.view addSubview:pickerDis];
    [pickerDis setClient:self];
    pickerDis.hidden = YES;
    [pickerDis addTheElement:arrayCatName];
}

-(void)datareload:(NSNotificationCenter *)notificatiion
{
    NSLog(@"%s",__PRETTY_FUNCTION__);
    [self  tableViewSettingWithRad:50];
}
-(IBAction)clickToBackBtn:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)tableViewSettingWithRad:(NSInteger)radius
{
//    if(TESTING)
//        radius = 20000;
    
    
    
    NSLog(@"!!!_____>>>>>~~~~~%@",[ModalController  getContforKey:RADSAVEDSAT]);
    
    if([ModalController  getContforKey:KsSWITCHEDMETER] )
        radius = [[ModalController  getContforKey:RADSAVEDSAT] integerValue];
    else 
    {
        radius = 1;
    }
    
    if(TESTING)
        radius = 20000;
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:URLDATA]];
    
    [request setRequestMethod:@"POST"];
    [request setPostValue:locationUser.strUserLat forKey:BASELAT];
    [request setPostValue:locationUser.strUserLong forKey:BASELONG];
//    [request setPostValue:@"999999"  forKey:@"City"];

    [request setPostValue:[NSString stringWithFormat:@"%d",radius] forKey:BASEDIS];
    [request setPostValue:@"" forKey:BASEIND];
    [request setPostValue:@"" forKey:BASECAT];
    [request setPostValue:@"" forKey:kSubCatId];
    
    [request setDelegate:self];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText = @"Loading...";

    [request startAsynchronous];
    
}

#define mark -ASIHTTP request delegates-


- (void)requestFinished:(ASIHTTPRequest *)request
{
    
    [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
    
    if(LOGOFF == 1) NSLog(@"I have got data------->>>>>%@",[request responseString]);
    
    NSDictionary *_xmlDictionaryData = [[XMLReader dictionaryForXMLData:[request responseData] error:nil] retain];
    
    if(LOGOFF == 1) NSLog(@"%@",_xmlDictionaryData);
    
    arrayNearBy = [[NSMutableArray alloc] init];
    
    arrayAllData = [[NSMutableArray  alloc] init];
    
    
    if([[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"])
    {
        if([[[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"] isKindOfClass:[NSArray class]])
            arrayNearBy  = [[NSMutableArray alloc] initWithArray:[[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"]];
        
        else
        {
            arrayNearBy = [[NSMutableArray alloc] init];
            [arrayNearBy addObject:[[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"]];
        }
        
        arrayAllData  = [[NSMutableArray  alloc] initWithArray:arrayNearBy];
    }
    [self loadMap];
}


- (void)requestFailed:(ASIHTTPRequest *)request
{
    [MBProgressHUD  hideHUDForView:self.navigationController.view
                          animated:YES];

    [ModalController showTheAlertWithMsg:@"Error in network" withTitle:@"Failed" inController:self];
}

-(void)reloadMap
{
    [self tableViewSettingWithRad:50];
}


-(void)loadMap
{
    if(customMap)
    {
        [customMap removeFromSuperview];
        [customMap release];        
        customMap = nil;
    }   
    
    customMap = [[CustomMapView alloc] initWithFrame:self.view.bounds];
    customMap.client = self;	
    customMap.mapType = MKMapTypeStandard;
    customMap.showsUserLocation = YES;
    [self.view insertSubview:customMap atIndex:1];
    
    arrayLatLong = [[NSMutableArray alloc] init];
    
    if(isFromDetail == 0)
    {
        NSLog(@"here");
        arrayMapLocs = [[NSMutableArray alloc] initWithArray:arrayNearBy];
    }
    
    for(int i=0;i<[arrayMapLocs count];i++)
    {
        NSMutableDictionary *dictLong = [[NSMutableDictionary alloc] init];
        [dictLong setObject:[[arrayMapLocs objectAtIndex:i ]objectForKey:FIELDLAT] forKey:FIELDLAT];
        [dictLong setObject:[[arrayMapLocs objectAtIndex:i ]objectForKey:FIELDLONG] forKey:FIELDLONG];
        [dictLong setObject:[[arrayMapLocs objectAtIndex:i ]objectForKey:FIELDNAME] forKey:@"title"];
        
        [arrayLatLong addObject:dictLong];
        UIBarButtonItem *btn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadMap)];
        self.navigationItem.rightBarButtonItem = btn;
        [dictLong release];
    }
    
    if(self.isFromDetail == 1)
    {
        UIButton *btnBack=[UIButton buttonWithType:UIButtonTypeCustom];
        [btnBack setFrame:CGRectMake(0, 10, 50, 30)];
        [btnBack setImage:[UIImage imageNamed:@"Back.png"] forState:UIControlStateNormal];
        [btnBack addTarget:self action:@selector(clickToBackBtn:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:btnBack];
        
        UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"Get Direction" 
                                                                style:UIBarButtonItemStyleDone 
                                                               target:self 
                                                               action:@selector(Direction)];
        self.navigationItem.rightBarButtonItem = btn;
        [btn release];
    }
    
    [customMap customizeMap:arrayLatLong];
   
//      CLLocationCoordinate2D centerCoord = { 52.8077920, -1.6471350 };
    CLLocationCoordinate2D centerCoord = { locationUser.userloc.coordinate.latitude, locationUser.userloc.coordinate.longitude };
    [customMap setCenterCoordinate:centerCoord
                         zoomLevel:8
                          animated:NO];
}

#pragma mark -clickAtindex-

-(void)clickAtindex:(NSInteger)index
{
    if(self.isFromDetail == 1)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        DetailsViewController *detailController = [[DetailsViewController    alloc] initWithNibName:@"DetailsViewController_Nw" bundle:nil];
        
        detailController.dictInfo = [[NSMutableDictionary alloc] initWithDictionary:[arrayNearBy objectAtIndex:index]];
        detailController.isFromFav = 0;
        detailController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailController
                                             animated:YES];
        [detailController release];

    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
